package com.zdkj.subway.stm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.dto.UserInfo;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.beantools.CompareFileds;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.exceltools.IExcelParser;
import com.zdkj.common.core.util.R;
import com.zdkj.common.core.util.SpringContextHolder;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.common.sequence.sequence.Sequence;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.dto.in.SwMessageDTO;
import com.zdkj.subway.stm.dto.in.SwStOperateLogDTO;
import com.zdkj.subway.stm.dto.out.SwStCycleDTO;
import com.zdkj.subway.stm.dto.out.SwStCycleExportDTO;
import com.zdkj.subway.stm.dto.out.SwStCycleExportInDTO;
import com.zdkj.subway.stm.dto.out.SwStCycleExportOutDTO;
import com.zdkj.subway.stm.entity.SwParamStation;
import com.zdkj.subway.stm.entity.SwStCycle;
import com.zdkj.subway.stm.entity.SwStCycleApply;
import com.zdkj.subway.stm.enums.CycleEnum;
import com.zdkj.subway.stm.enums.MessageEnums;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.handler.LogHandler;
import com.zdkj.subway.stm.mapper.SwParamStationMapper;
import com.zdkj.subway.stm.mapper.SwStCycleMapper;
import com.zdkj.subway.stm.service.SwStCycleApplyService;
import com.zdkj.subway.stm.service.SwStCycleService;
import com.zdkj.subway.stm.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 站间调票(线网)
 *
 * @author 陈博
 * @date 2020-01-14 14:39:01
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swstcycle")
@Api(value = "swstcycle", tags = "站间调票管理")
public class SwStCycleController {

    private static final String CycleIn = "0";
    private static final String CycleOut = "1";

    private final SwStCycleService swStCycleService;
    private final SupportService supportService;
    private final SystemUserService systemUserService;
    private final SwStCycleApplyService swStCycleApplyService;
    private final SwParamStationMapper swParamStationMapper;

    @Resource(name = "invoiceSequence")
    private Sequence invoiceSequence;
    @Resource
    SwStCycleMapper swStCycleMapper;


    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param swStCycle 站间调票
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getPage(Page page, SwStCycle swStCycle, String inOrOut) {
        String dateCondition = swStCycle.getOutTimeDTO();
        LambdaQueryWrapper<SwStCycle> queryWrapper = Wrappers.query(swStCycle).orderByDesc("in_time","out_time","create_time").lambda();
        if (StringUtils.isNotEmpty(swStCycle.getSpecialCardNoSearch())) {
            queryWrapper.likeRight(SwStCycle::getSpecialCardNo, swStCycle.getSpecialCardNoSearch());
        }

        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.likeRight(SwStCycle::getOutTime, dateCondition);
        }
        List<String> dateConditiondr = swStCycle.getDates1();
        List<String> dateConditiondc = swStCycle.getDates2();
        if (ObjectUtil.isNotEmpty(dateConditiondr) && !"".equals(dateConditiondr.get(0))) {
            queryWrapper.apply("DATE_FORMAT(IN_TIME,'%Y-%m-%d') between DATE_FORMAT('"+dateConditiondr.get(0)+"','%Y-%m-%d') and DATE_FORMAT('"+dateConditiondr.get(1)+"','%Y-%m-%d')");
        }
        if (ObjectUtil.isNotEmpty(dateConditiondc) && !"".equals(dateConditiondc.get(0))) {
            queryWrapper.apply("DATE_FORMAT(OUT_TIME,'%Y-%m-%d') between DATE_FORMAT('"+dateConditiondc.get(0)+"','%Y-%m-%d') and DATE_FORMAT('"+dateConditiondc.get(1)+"','%Y-%m-%d')");
        }else{
            /*if(ObjectUtil.isNotEmpty(dateConditiondr)){
                queryWrapper.between(SwStCycle::getOutTime, dateConditiondr.get(0), dateConditiondr.get(1));
            }*/
        }
        String lineCode = SecurityUtils.getUser().getLineCode();
        String stationCode = SecurityUtils.getUser().getStationCode();
        if (SecurityUtils.getUser().getBelongToLine()) {
            return R.ok(swStCycleService.page(page, queryWrapper));
        } else {
            /**
             * 查询 本车站，已经确认过通知的调票记录
             */
            if (inOrOut.equals(CycleIn)) {
                if (ObjectUtil.isNotEmpty(dateConditiondr)) {
                    queryWrapper.between(SwStCycle::getInTime, dateConditiondr.get(0), dateConditiondr.get(1));
                }
                if (ObjectUtil.isNotEmpty(dateConditiondc)) {
                    queryWrapper.between(SwStCycle::getInTime, dateConditiondc.get(0), dateConditiondc.get(1));
                }
                return R.ok(swStCycleService.page(page,
                        queryWrapper
                                .eq(SwStCycle::getNoticeStatus, CycleEnum.NOTICE_SUC.getCode())
                                .eq(SwStCycle::getInLineCode,lineCode)
                                .and(i -> i.eq(SwStCycle::getInStationCode, stationCode))
                                .eq(SwStCycle::getIsConfirmIn, CycleEnum.NOTICE_SUC.getCode())
                                .eq(SwStCycle::getIsConfirmOut, CycleEnum.NOTICE_SUC.getCode())
                ));
            } else if (inOrOut.equals(CycleOut)) {
                if (ObjectUtil.isNotEmpty(dateConditiondr)) {
                    queryWrapper.between(SwStCycle::getInTime, dateConditiondr.get(0), dateConditiondr.get(1));
                }
                if (ObjectUtil.isNotEmpty(dateConditiondc)) {
                    queryWrapper.between(SwStCycle::getInTime, dateConditiondc.get(0), dateConditiondc.get(1));
                }
                return R.ok(swStCycleService.page(page,
                        queryWrapper
                                .eq(SwStCycle::getNoticeStatus, CycleEnum.NOTICE_SUC.getCode())
                                .eq(SwStCycle::getOutLineCode,lineCode)
                                .and(i -> i.eq(SwStCycle::getOutStationCode, stationCode))
                                .eq(SwStCycle::getIsConfirmIn, CycleEnum.NOTICE_SUC.getCode())
                                .eq(SwStCycle::getIsConfirmOut, CycleEnum.NOTICE_SUC.getCode())
                ));
            } else {
                return R.failed("请传入inOrOut参数确定调入或者调出");
            }

        }
    }


    /**
     * 获取某天调入调出数量供，库存变更使用
     *
     * @param localDate 日期
     * @param station   车站
     * @return
     */
    @ApiOperation(value = "获取某天调入调出数量供，库存变更使用", notes = "获取某天调入调出数量供，库存变更使用")
    @GetMapping("/getTicketChange/{localDate}/{station}")
    public R getTicketChange(@PathVariable LocalDate localDate, @PathVariable String station) {
        return R.ok(swStCycleService.getTicketChange(localDate, station));
    }


    /**
     * 新增站间调票
     *
     * @param swStCycle 站间调票
     * @return R
     */
    @ApiOperation(value = "新增站间调票", notes = "新增站间调票")
    @SysLog("新增站间调票")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_add')")
    public R save(@RequestBody SwStCycle swStCycle) {
        if (swStCycle.getCardTypeParam().equals("TSGZK")) {
            if(StringUtils.isEmpty(swStCycle.getSpecialCardNo())){
                return R.failed("特殊工作卡需填写特殊工作卡卡号！");
            }
        }
        SwStCycle defaultObj = ObjectValueUtils.getDefaultObj(SwStCycle.class);
        BeanUtil.copyProperties(swStCycle, defaultObj, CopyOptions.create()
                .setIgnoreProperties(BeanPropertyUtils.getNullAndEmptyPropertyNames(swStCycle)));
        /**
         * 插入流水号
         */
        defaultObj.setOrderNum(invoiceSequence.nextNo());
        return R.ok(swStCycleService.save(defaultObj));
    }

    /**
     * 修改站间调票
     *
     * @param swStCycle 站间调票
     * @return R
     */
    @ApiOperation(value = "修改站间调票", notes = "修改站间调票")
    @SysLog("修改站间调票")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_edit')")
    public R updateById(@RequestBody SwStCycle swStCycle) {
        SwStCycle before = swStCycleService.getById(swStCycle.getId());
        SwStCycleApply swStCycleApply = swStCycleApplyService.getById(before.getApplyId());
        swStCycle.setHandleStatus(CycleEnum.HANDLE_STATUS_IS.getCode());
        if (swStCycleService.updateById(swStCycle)) {
            //调出站编辑完调出数量等信息将调票申请的办理状态修改为待接收
            if(swStCycleApply != null){
                SwStCycleApply newSwStCycleApply = new SwStCycleApply();
                newSwStCycleApply.setId(swStCycleApply.getId());
                newSwStCycleApply.setHandleStatus(CycleEnum.HANDLE_STATUS_IS.getCode());
                swStCycleApplyService.updateById(newSwStCycleApply);
            }
            Map<String, Map> fileds = CompareFileds
                    .compareFields(before, swStCycle, CompareFileds.getFileds(swStCycle));
                if(null==fileds){
                    return R.ok();
                }else{
                    List<SwStOperateLogDTO> list = LogHandler.setLogParms(fileds, before);
                    return R.ok(supportService.logSaveBatch(list));
                }
        } else {
            return R.failed("修改站间调票记录失败");
        }
    }


    /**
     * 调入站一键确认
     *
     * @param swStCycle 调入站一键确认
     * @return R
     */
    @ApiOperation(value = "调入站一键确认", notes = "调入站一键确认")
    @SysLog("调入站一键确认")
    @PutMapping("updateConfirm")
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_one_edit')")
    public R updateConfirm(@RequestBody List<SwStCycle> swStCycle) {
        ArrayList<SwStCycle> swStCycles = new ArrayList<>();
        ArrayList<SwStCycleApply> stCycleApplys = new ArrayList<>();
        for (SwStCycle stCycle : swStCycle) {
            stCycle = swStCycleService.getById(stCycle.getId());
            SwStCycleApply swStCycleApply = new SwStCycleApply();
            /**
             * 初步筛选调出确认过的数据进行默认填充，可能会出现调出确认了，但线下票没送，先确认了。
             */
            if (stCycle.getIsOut().equals(CycleEnum.CONFIRM_SUC.getCode())) {
                stCycle.setHandleStatus(CycleEnum.HANDLE_STATUS_COMPLETE.getCode());
                stCycle.setIsIn(CycleEnum.CONFIRM_SUC.getCode());
                stCycle.setInNumber(stCycle.getOutToNumber());
//                stCycle.setInTime(LocalDateTime.now());
                stCycle.setInPerson(SecurityUtils.getUser().getNikeName());
                stCycle.setInPersonCode(SecurityUtils.getUser().getUserCode());
                swStCycles.add(stCycle);
                swStCycleApply = swStCycleApplyService.getById(stCycle.getApplyId());
                //调入站一键确认时同时修改申请表办理状态为已完成
                if(swStCycleApply != null){
                    swStCycleApply.setHandleStatus(CycleEnum.HANDLE_STATUS_COMPLETE.getCode());
                    stCycleApplys.add(swStCycleApply);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(swStCycles)){
            swStCycleService.updateBatchById(swStCycles);
        }
        //调入站一键确认时同时修改申请表办理状态
        if(CollectionUtil.isNotEmpty(stCycleApplys)){
            swStCycleApplyService.updateBatchById(stCycleApplys);
        }
        return R.ok();

    }


    /**
     * 通知车站
     *
     * @param swStCycle 通知车站
     * @return R
     */
    @ApiOperation(value = "通知车站", notes = "通知车站")
    @SysLog("通知车站")
    @PutMapping("/notice")
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_notice')")
    public R noticeById(@RequestBody List<SwStCycle> swStCycle) {
        /**
         * 此处未做任何校验，传进来的值全部把通知状态改为已通知。
         */
        PigxUser user = SecurityUtils.getUser();
        for (SwStCycle stCycle : swStCycle) {
            QueryWrapper<SwParamStation> inQueryWrapper = new QueryWrapper<>();
            inQueryWrapper.eq("CODE", stCycle.getInStationCode());
            SwParamStation inStation = swParamStationMapper.selectOne(inQueryWrapper);

            QueryWrapper<SwParamStation> outQueryWrapper = new QueryWrapper<>();
            outQueryWrapper.eq("CODE", stCycle.getOutStationCode());
            SwParamStation outStation = swParamStationMapper.selectOne(outQueryWrapper);

            SwMessageDTO swMessageDTO = new SwMessageDTO();
            swMessageDTO.setMsgType("通知");
            swMessageDTO.setTitle("线路发起站间调票");
            swMessageDTO.setLineCode(stCycle.getOutLineCode());
            swMessageDTO.setStationCode(stCycle.getOutStationCode());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = stCycle.getInTime().format(formatter);
            swMessageDTO.setContent(formattedDateTime + inStation.getName() + "从" + outStation.getName() + "调票");
            swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.TICKET_DISTRUBUTION_NOTICE_AUDIT_URL.getUrl());
            swMessageDTO.setCreatorId(user.getId());
            swMessageDTO.setCreatorName(user.getNikeName());
            swMessageDTO.setCreateTime(LocalDateTime.now());
            swMessageDTO.setDelFlag("0");

            supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);

            swMessageDTO.setLineCode(stCycle.getInLineCode());
            swMessageDTO.setStationCode(stCycle.getInStationCode());
            supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);

            /**
             * 更改通知状态   为1  已通知
             */
            stCycle.setNoticeStatus(CycleEnum.CONFIRM_SUC.getCode());
            swStCycleService.updateById(stCycle);
            //TODO 通知形式待
        }

        return R.ok();
    }

    /**
     * 取消通知车站
     * 此处将传进来的值进行简单筛选，去掉已经确认过的记录，确认过的记录不能撤销通知了
     *
     * @param swStCycle 取消通知车站
     * @return R
     */
    @ApiOperation(value = "取消通知车站", notes = "取消通知车站")
    @SysLog("取消通知车站")
    @PutMapping("/cancelNotice")
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_cancel_notice')")
    public R cancelNoticeById(@RequestBody List<SwStCycle> swStCycle) {

        //记录撤回失败记录流水号
        ArrayList<String> strings = null;
        for (SwStCycle stCycle : swStCycle) {
            if (stCycle.getIsConfirmOut().equals(CycleEnum.CONFIRM_SUC.getCode())) {
                strings = new ArrayList<>();
                strings.add(stCycle.getOrderNum());
                break;
            }
            /**
             * 更改通知状态   为0  未通知
             */
            stCycle.setNoticeStatus(CycleEnum.CONFIRM_FAIL.getCode());
            swStCycleService.updateById(stCycle);
        }
        if (strings != null) {
            R.failed(strings, "撤回失败流水号集合");
        }

        return R.ok("所有记录都修改成功");
    }

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param swStCycle 站间调票
     * @return
     */
    @ApiOperation(value = "分页关联查询", notes = "分页关联查询")
    @GetMapping("/pageMapper")
    public R getSwStCyclePage(Page page, SwStCycle swStCycle) {
        R<UserInfo> info = systemUserService.info();
        String stationCode = info.getData().getSysUser().getStationCode();
        if (info.getData().getSysUser().getBelongToLine()) {
            return R.ok(swStCycleService.pageMapper(page,
                    Wrappers.query(swStCycle)
                            .allEq(SelMapUtils.getSwStCycleMap(swStCycle), false)));
        } else {
            return R.ok(swStCycleService.pageMapper(page,
                    Wrappers.query(swStCycle)
                            .allEq(SelMapUtils.getSwStCycleMap(swStCycle), false)
                            .eq("a.IS_CONFIRM_OUT", CycleEnum.NOTICE_SUC.getCode())
                            .eq("a.IS_CONFIRM_OUT", CycleEnum.NOTICE_SUC.getCode())
                            .and(i -> i.eq("a.OUT_STATION_CODE", stationCode)
                                    .or().eq("a.IN_STATION_CODE", stationCode))));
        }
    }

    /**
     * 通过id查询站间调票
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStCycleService.getById(id));
    }

    /**
     * 通过id删除站间调票
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除站间调票", notes = "通过id删除站间调票")
    @SysLog("通过id删除站间调票")
    @DeleteMapping("/{id}")
    //@PreAuthorize("@pms.hasPermission('stm_swstcycle_del')")  线网层级也需要删除功能，屏蔽 20240521
    public R removeById(@PathVariable Integer id) {
        SwStCycle before = swStCycleService.getById(id);
        UpdateWrapper<SwStCycle> wrapper = new UpdateWrapper<>();
        wrapper.set("DEL_FLAG", 1);
        wrapper.eq("id", id);
        before.setDelFlag("1");
        swStCycleService.update(wrapper);
//        swStCycleService.removeById(id);
        SwStOperateLogDTO swStOperateLogDTO = LogHandler.setDelLog(before);
        return R.ok(supportService.logSave(swStOperateLogDTO));
    }


    /**
     * 导出
     *
     * @param ids      分页对象
     * @param inOrOut      分页对象
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/export")
    //@PreAuthorize("@pms.hasPermission('stm_swstcycle_export')")
    public void getSwStCycleExport(@RequestParam(value = "ids") List<Integer> ids,@RequestParam(value = "inOrOut") String inOrOut, HttpServletResponse response) throws IOException {
        List<SwStCycleExportDTO> list = new ArrayList<>();
        List<SwStCycleExportInDTO> listIn = new ArrayList<>();
        List<SwStCycleExportOutDTO> listOut = new ArrayList<>();
        List<SwStCycle> swStCycleList;
        PigxUser user = SecurityUtils.getUser();
        Map<String,String> params = new HashMap<>();
        if (user.getBelongToLine()) {
            params.put("flag","0");
            swStCycleList = swStCycleMapper.queryExport(ids,params);
        } else {
            if (inOrOut.equals(CycleIn)) {
                params.put("flag","1");
                params.put("lineCode",user.getLineCode());
                params.put("stationCode",user.getStationCode());
                params.put("isCongirmIn",CycleEnum.NOTICE_SUC.getCode());
                swStCycleList = swStCycleMapper.queryExport(ids,params);
            } else if (inOrOut.equals(CycleOut)) {
                params.put("flag","2");
                params.put("lineCode",user.getLineCode());
                params.put("stationCode",user.getStationCode());
                params.put("isCongirmOut",CycleEnum.NOTICE_SUC.getCode());
                swStCycleList = swStCycleMapper.queryExport(ids,params);
            } else {
                swStCycleList = new ArrayList<>();
            }
        }
        R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_SYCLE_HANDLE_STATUS);
        List<SysDictItem> dictData = inputDataStatus.getData();
        for (SwStCycle record : swStCycleList) {
            Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
            record.setHandleStatus(map.get(record.getHandleStatus()));
        }
        if(user.getBelongToLine()){
            swStCycleList.forEach(i -> {
                SwStCycleExportDTO dto = new SwStCycleExportDTO();
                BeanUtils.copyProperties(i, dto);
                list.add(dto);
            });
            String fileName = URLEncoder.encode("站间调票", "UTF-8");
            ServletOutputStream outputStream  = null;
			try{
				
               response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
           	   outputStream = response.getOutputStream();	
			   EasyExcel.write(response.getOutputStream(), SwStCycleExportDTO.class).registerConverter(new LocalDateTimeConverter())
                    .registerConverter(new LocalDateConverter()).sheet("站间调票").doWrite(list);
			}catch(Exception e){
            	outputStream.close();
            	
            }
		
			

        }else {
            if (inOrOut.equals(CycleIn)) {
                swStCycleList.forEach(i -> {
                    SwStCycleExportInDTO dto = new SwStCycleExportInDTO();
                    BeanUtils.copyProperties(i, dto);
                    listIn.add(dto);
                });
                String fileName = URLEncoder.encode("调入站站间调票记录", "UTF-8");
				ServletOutputStream outputStream  = null;
			    try{
                     outputStream = response.getOutputStream();	
					 response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
                     EasyExcel.write(outputStream, SwStCycleExportInDTO.class).registerConverter(new LocalDateTimeConverter())
                        .registerConverter(new LocalDateConverter()).sheet("站间调票").doWrite(listIn);
                }catch(Exception e){
            	    outputStream.close();
            	
                }
            } else if (inOrOut.equals(CycleOut)) {
                swStCycleList.forEach(i -> {
                    SwStCycleExportOutDTO dto = new SwStCycleExportOutDTO();
                    BeanUtils.copyProperties(i, dto);
                    listOut.add(dto);
                });
                String fileName = URLEncoder.encode("调出站站间调票记录", "UTF-8");
				ServletOutputStream outputStream  = null;
                try{
                     outputStream = response.getOutputStream();	
				     response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
                     EasyExcel.write(outputStream, SwStCycleExportOutDTO.class).registerConverter(new LocalDateTimeConverter())
                        .registerConverter(new LocalDateConverter()).sheet("站间调票").doWrite(listOut);
				}catch(Exception e){
            	  outputStream.close();
            	
                }

            }
        }
    }

    @PostMapping(value = "/import")
    @SysLog("导入站间调票信息")
    @PreAuthorize("@pms.hasPermission('stm_swstcycle_import')")
    public R importExcel(@RequestParam("file") MultipartFile multipartFile) {
        try {
            Sheet sheet = ExcelUtilsStm.inport(multipartFile);
            IExcelParser excelParser = SpringContextHolder.getBean("commonExcelParse");
            List<SwStCycle> list = excelParser.parse(sheet, new SwStCycleDTO());
            swStCycleService.saveBatch(list);
        } catch (Exception e) {
            return R.failed(e.getMessage(), "导入失败");
        }
        return R.ok("1", "导入成功");
    }
}
